package com.cheng.shirossochapter02.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Create by cheng on 2019/5/17 23:25
 */
@Controller
public class LoginController {

    @GetMapping("/login")
    public String login(HttpServletRequest request) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return "/index";
        }
        return "/login";
    }

    @PostMapping("/login")
    public String login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);
        return "/index";
    }

//    @RequestMapping("/logout")
//    @ResponseBody
//    public String logout(HttpServletRequest request, HttpSession session) {
//        SecurityUtils.getSubject().logout();
//        return "退出";
//    }

//    @RequestMapping("/out")
//    public String logout() {
//        return "redirect:" + ShiroConfig.outUrl;
//    }


    @RequestMapping("/test1")
    @ResponseBody
    public String test1() {
        return "成功";
    }


    @RequestMapping("/test2")
    @ResponseBody
    public String test2() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "已登录";
        } else {
            return "未登陆";
        }
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        System.out.println(session.getId());
        System.out.println(SecurityUtils.getSubject().getSession().getId());
        //获取session的Id
        String sessionId = session.getId();
        //将session的Id存储到名字为JSESSIONID的cookie中
        Cookie cookie = new Cookie("JSESSIONID", sessionId);
        //设置cookie的有效路径
        cookie.setPath(request.getContextPath());
        cookie.setDomain("localhost");
        response.addCookie(cookie);
        return "test";
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request, HttpSession session) {
        System.out.println(session.getId());
        System.out.println(SecurityUtils.getSubject().getSession().getId());
        return "/index";
    }

}
